package com.summer.data.connection.source;

import com.summer.data.connection.*;
import com.summer.data.connection.session.NormalSession;
import com.summer.data.connection.session.TransactionSession;
import com.summer.data.dialect.DatabaseProductID;
import com.summer.data.dialect.Dialect;
import com.summer.data.dialect.DialectCenter;
import com.summer.data.exception.SqlException;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

/**
 * @author 345480567@qq.com
 */
public abstract class AbstractSessionFactory implements SessionFactory {

    protected Dialect dialect;

    public AbstractSessionFactory(Dialect dialect) {
        this.dialect = dialect;
    }

    @Override
    public Session openSession() {
        return new NormalSession(this);
    }

    @Override
    public Transaction openTransactional(TransactionDef txDef) {
        return new TransactionSession(this, txDef);
    }

    protected void initDialect() {
        if (dialect == null) {
            Connection connection = getConnection();
            try {
                DatabaseMetaData databaseMetaData = connection.getMetaData();
                String dbProdName = databaseMetaData.getDatabaseProductName();
                int majorVersion = databaseMetaData.getDatabaseMajorVersion();
                DatabaseProductID productID = new DatabaseProductID(dbProdName, majorVersion);
                dialect = DialectCenter.getDialect(productID);
            } catch (SQLException e) {
                throw new SqlException(e);
            } finally {
                Utils.closeConnection(connection);
            }
        }
    }

    @Override
    public Dialect getDialect() {
        if (dialect == null) {
            initDialect();
        }
        return dialect;
    }

}
